<template>
  <div class="user-detail">
    <Card class="user-detail__card">
      <p class="user-detail__title" slot="title">基本资料</p>
      <div class="user-detail__content">
        <img :src="user.avatar" alt="头像" class="user-detail__image" />
        <div class="user-detail__right">
          <div class="user-detail__username">{{ user.username }}</div>
          <div class="user-detail__items">
            <span>ID：{{ user._id }}</span>
            <span>openID：{{ user.openid }}</span>
            <span>手机号码：{{ user.mobile || '未知' }}</span>
            <span
              >来源：{{ $consts.REGISTE_SOURCE[user.source] || '未知' }}</span
            >
            <span>注册时间：{{ user.create_time }}</span>
            <span>
              书币数量：
              <b>{{ user.amount }}枚</b>
              <Button
                type="text"
                shape="circle"
                icon="md-create"
                class="user-detail__edit-icon"
                @click="handleChangeAmount"
              ></Button>
            </span>
            <span>阅读时长：{{ user.read_time }}</span>
            <span>
              备注：{{ user.remark || '暂无' }}
              <Button
                type="text"
                shape="circle"
                icon="md-create"
                class="user-detail__edit-icon"
                @click="handleChangeRemark"
              ></Button>
            </span>
            <span></span>
          </div>
        </div>
      </div>
    </Card>
    <Card class="user-detail__card">
      <p class="user-detail__title" slot="title">
        会员信息
        <Button
          type="primary"
          size="small"
          icon="ios-add"
          class="user-detail__title-btn"
          @click="handleAddMember('add')"
          >新增</Button
        >
      </p>
      <Table
        :columns="memberColumns"
        :data="memberData"
        no-data-text="该用户还不是会员"
      ></Table>
    </Card>
    <Card class="user-detail__card">
      <p class="user-detail__title" slot="title">阅读记录</p>
      <Table
        :columns="bookListColumns"
        :data="bookList"
        no-data-text="该用户还没有阅读记录"
      ></Table>
    </Card>
    <!-- <Card class="user-detail__card">
      <p class="user-detail__title" slot="title">分享记录</p>
      <Table :columns="memberColumns" :data="[]" no-data-text="该用户还没有阅读记录"></Table>
    </Card> -->
    <!-- 弹窗 -->
    <Modal
      :title="modal.title"
      v-model="modal.show"
      @on-ok="handleModalConfirm"
      @on-cancel="handleModalCancel"
    >
      <template v-if="modal.type === 'member'">
        <p style="margin-bottom: 10px">选择会员类型:</p>
        <Select v-model="modal.data.name" style="margin-bottom: 10px">
          <Option value="年付会员">年付会员</Option>
          <Option value="半年付会员">半年付会员</Option>
          <Option value="季付会员">季付会员</Option>
          <Option value="月付会员">月付会员</Option>
          <Option value="7天体验会员">7天体验会员</Option>
          <Option value="自定义天数会员">自定义天数会员</Option>
        </Select>
        <template v-if="modal.data.name === '自定义天数会员'">
          <p style="margin-bottom: 10px">请输入会员天数:</p>
          <Input
            type="number"
            v-model="modal.data.days"
            autofocus
            placeholder="请输入会员天数"
          />
        </template>
      </template>
      <template v-if="modal.type === 'amount'">
        <p style="margin-bottom: 10px">请输入阅读币数量:</p>
        <Input
          type="number"
          v-model="modal.data.amount"
          autofocus
          placeholder="请输入阅读币数量"
        />
      </template>
      <template v-if="modal.type === 'remark'">
        <p style="margin-bottom: 10px">备注用来给对用户做注释:</p>
        <Input
          type="textarea"
          row="5"
          v-model="modal.data.remark"
          autofocus
          placeholder="请输入备注"
        />
      </template>
    </Modal>
  </div>
</template>

<script>
import http from '@/utils/http';
import moment from 'moment';
import { formatTimeToDDHHMMSS } from '@/utils/format-time';
moment.locale('zh-cn');

export default {
  name: 'user-detail',

  data() {
    return {
      user: {},
      bookList: [],
      comment: [],
      share: [],
      value: '',
      modal: {
        show: false,
        type: 'member',
        title: '',
        data: {},
      },
      memberColumns: [
        {
          title: '会员名称',
          key: 'name',
          align: 'center',
        },
        {
          title: '剩余时间',
          key: 'expired',
          align: 'center',
          render: (h, params) => {
            return <span>{moment(params.row.expired).fromNow()}</span>;
          },
        },
        {
          title: '到期时间',
          key: 'expired',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.expired).format('YYYY/MM/DD HH:MM:SS')}
              </span>
            );
          },
        },
        {
          title: '操作',
          key: 'handle',
          align: 'center',
          render: (h, params) => {
            return (
              <div>
                <Button
                  type="primary"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleMemberChange(params.row)}
                >
                  修改
                </Button>
                <Button
                  type="error"
                  size="small"
                  class="text-red"
                  onClick={() => this.handleMemberDelete(params.row)}
                >
                  删除
                </Button>
              </div>
            );
          },
        },
      ],
      bookListColumns: [
        {
          title: '书籍名称',
          key: 'name',
          align: 'center',
          render: (h, params) => {
            return <span>{params.row.bookid.name}</span>;
          },
        },
        {
          title: '更新状态',
          key: 'update_status',
          align: 'center',
          render: (h, params) => {
            return <span>{params.row.bookid.update_status}</span>;
          },
        },
        {
          title: '最新章节',
          key: 'newest_chapter',
          align: 'center',
          render: (h, params) => {
            return <span>第{params.row.bookid.newest_chapter}章</span>;
          },
        },
        {
          title: '更新时间',
          key: 'update_time',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.bookid.update_time).format(
                  'YYYY/MM/DD HH:MM:SS'
                )}
              </span>
            );
          },
        },
        {
          title: '最近阅读时间',
          key: 'time',
          align: 'center',
          render: (h, params) => {
            return (
              <span>
                {moment(params.row.time).format('YYYY/MM/DD HH:MM:SS')}
              </span>
            );
          },
        },
        {
          title: '阅读进度',
          key: 'time',
          align: 'center',
          render: (h, params) => {
            return <span>第{params.row.read.num}章</span>;
          },
        },
        {
          title: '是否订阅',
          key: 'time',
          align: 'center',
          render: (h, params) => {
            return <span>{params.row.rss ? '是' : '否'}</span>;
          },
        },
      ],
    };
  },

  computed: {
    memberData() {
      return this.user.member ? [this.user.member] : [];
    },
  },

  methods: {
    fetchUserInfo() {
      http({
        method: 'GET',
        url: '/api/admin/user/info',
        params: {
          userid: this.$route.params.id,
        },
        operation: '获取用户画像',
      }).then((res) => {
        if (res.ok) {
          res.data.user.create_time = moment(res.data.user.create_time).format(
            'YYYY/MM/DD HH:MM:SS'
          );
          res.data.user.read_time = formatTimeToDDHHMMSS(
            res.data.user.read_time
          );
          this.user = res.data.user;
          this.bookList = res.data.bookList;
          this.comment = res.data.comment;
          this.share = res.data.share;
        }
      });
    },

    handleChangeAmount() {
      this.modal.show = true;
      this.modal.type = 'amount';
      this.modal.title = '修改阅读币';
      this.modal.data = { amount: this.user.amount };
    },

    handleChangeRemark() {
      this.modal.show = true;
      this.modal.type = 'remark';
      this.modal.title = '修改备注';
      this.modal.data = { remark: '' };
    },

    handleAddMember(name) {
      if (name === 'add') {
        this.modal.show = true;
        this.modal.type = 'member';
        this.modal.title = '新增会员';
        this.modal.data = { name: '', days: '' };
      } else {
        this.modal.show = true;
        this.modal.title = '修改会员';
        this.modal.data = { name: this.user.member.name };
      }
    },

    handleModalConfirm() {
      if (this.modal.type === 'amount') {
        http({
          method: 'PUT',
          url: `/api/admin/user/${this.$route.params.id}`,
          data: {
            amount: this.modal.data.amount,
          },
          operation: '修改阅读币数量',
        }).then((res) => {
          if (res.ok) {
            this.$Message.success('修改成功');
            this.fetchUserInfo();
          }
        });
      } else if (this.modal.type === 'remark') {
        http({
          method: 'PUT',
          url: `/api/admin/user/${this.$route.params.id}`,
          data: {
            remark: this.modal.data.remark,
          },
          operation: '修改备注',
        }).then((res) => {
          if (res.ok) {
            this.$Message.success('修改成功');
            this.fetchUserInfo();
          }
        });
      } else if (this.modal.type === 'member') {
        http({
          method: 'POST',
          url: '/api/admin/member',
          data: {
            userid: this.$route.params.id,
            memberName: this.modal.data.name,
            days: this.modal.data.days,
          },
          operation: '修改会员',
        }).then((res) => {
          if (res.ok) {
            this.$Message.success('操作成功');
            this.fetchUserInfo();
          }
        });
      }
    },

    handleModalCancel() {
      this.modal.show = false;
      this.modal.title = '';
      this.modal.type = '';
      this.modal.data = {};
    },

    handleMemberChange() {
      this.modal.show = true;
      this.modal.title = '修改会员';
      this.modal.type = 'member';
      this.modal.data = {
        name: this.user.member.name,
        days: Math.ceil((this.user.member.expired - Date.now()) / (24 * 60 * 60 * 1000)),
      };
    },

    handleMemberDelete() {
      this.$Modal.confirm({
        title: '温馨提示',
        content: '确定要删除此用户的会员资格？',
        onOk: () => {
          http({
            method: 'DELETE',
            url: '/api/admin/member',
            data: {
              userid: this.$route.params.id,
            },
            operation: '删除会员',
          }).then((res) => {
            if (res.data && res.ok) {
              this.$Message.success('删除成功');
              this.fetchUserInfo();
            }
          });
        },
        onCancel: () => {},
      });
    },
  },

  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.params.id !== to.params.id) {
        vm.fetchUserInfo();
      }
    });
  },
};
</script>

<style lang="scss">
.user-detail {
  &__card {
    margin-bottom: 20px;
  }

  &__title {
    height: auto !important;
    display: flex !important;
    justify-content: space-between;
    align-items: center;
    line-height: 1;
    position: relative;
    padding-left: 6px;

    &::before {
      content: ' ';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-52%);
      display: inline-block;
      width: 2px;
      height: 12px;
      background: cornflowerblue;
    }
  }

  &__content {
    display: flex;
    align-items: flex-start;
    padding: 20px;
  }

  &__image {
    width: 72px;
    height: 72px;
    border-radius: 36px;
    margin-right: 30px;
  }

  &__right {
    flex: 1;
  }

  &__username {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  &__items {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    margin-bottom: -20px;

    & > span {
      display: inline-block;
      flex: 33%;
      text-align: left;
      line-height: 20px;
      font-size: 14px;
      margin-bottom: 20px;
    }
  }

  &__edit-icon {
    position: relative;
    outline: none;
    box-shadow: none !important;
    height: 20px !important;
    top: -2px;

    &:active &::after {
      background: #2b85e4;
    }

    &::after {
      content: ' ';
      position: absolute;
      left: 10px;
      top: 16px;
      width: 11px;
      height: 1px;
      background: #515a6e;
    }
  }
}
</style>
